<?php
namespace app\controllers\crontab;
use Yii;
use app\components\Site;
use app\models\Elog;
use app\components\TemplateMarket;
use app\models\marketing\MailTemplate;
/*
 * 手动处理模板数据模块
 * @author 刘刚 2018-3-1
 */
class DealTemplateDataController extends \app\base\Controller 
{
    
    /**
     * 初始化
     */
    public function init()
    {
//        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
    }
    
    /**
     * 以邮件模板最近1次发送时间算起，对超过60天未发送过，即系统自动将这些邮件模板，模板状态改为【关闭】
     * @reurn string
     * @author liugang 2018-3-1
     */
    public function actionUpdateTemplateStatus()
    {
        
        $curTime =  \yii::$app->bjTime->time();
       
        $dayStartTime = \yii::$app->bjTime->strtotime(\yii::$app->bjTime->date("Y-m-d",$curTime)." 00:00:00");
        $startTime60Ago =  $dayStartTime-3600*24*60;
        
        // 获取超过60天未生成分组的模板id
        $getSql = "select max(g.add_date) last_date,g.template_id from mail_template t join mail_group g on t.template_id = g.template_id where t.is_del = 0 and t.is_use = 1 and t.status = 1 group by g.template_id having last_date < {$startTime60Ago} ";
        
        $noUseTemplate60Ago = Yii::$app->db->createCommand($getSql)->queryAll();
        
        $templateIds = [];
        foreach($noUseTemplate60Ago as $noUseTemplate) {
            $templateIds[] = $noUseTemplate['template_id'];
        }
        
        // 将超过60天没有添加分组的模板关闭
        if($templateIds) {
            
            $updateSql = "update mail_template set status = 0 where template_id in(".join(',',$templateIds).") and is_del = 0 and is_use = 1 and status = 1";
            
            Yii::$app->db->createCommand($updateSql)->execute();
        }
        
        return '超过60天没有添加分组的模板成功关闭';
        
    }
    
    
    /*
     * 记录相关日志
     */
    private function writeLog($msg)
    {
        $date = yii::$app->bjTime->date("Y-m-d H:i:s");
        $today = yii::$app->bjTime->date("Ymd");
        $dir = yii::$app->getRuntimePath() . "/logs/" . yii::$app->bjTime->date("Ym");
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $filePath = $dir . "/do_channal_data_{$today}.log";
        $msg = "[{$date}] $msg" . PHP_EOL;
        file_put_contents($filePath, $msg, FILE_APPEND);
    }
}